/*
The main class which acts as an API layer between
the VizSpread application and Google Maps API
*/
function VMapper(mapElementID){
	this.map = new GMap2(document.getElementById(mapElementID));
	this.mapCentre =  new GLatLng(0, 0);
	this.map.setCenter(this.mapCentre);
	this.mapCentreAddress = "";
	this.mapData = new Array();
}

function loadMapCentre(id){
	var mapCentreContainer = document.getElementById(id);
	this.mapCentreAddress = mapCentreContainer.firstChild.nodeValue;
}

VMapper.prototype.loadMapCentre = loadMapCentre;

function loadMapData(data){
	this.mapData = data;
}

VMapper.prototype.loadMapData = loadMapData;

function setUpMarkers(){
	for (var i=0; i<this.mapData.length;i++){
		var jsonOb = this.mapData[i];
		var place = jsonOb.Placemark[0];
		var address = place.address;
		var point = new GLatLng(place.Point.coordinates[1],
								place.Point.coordinates[0]);
		
		html = place.address + '<br>' + '<b>Country code:</b> ' + place.AddressDetails.Country.CountryNameCode
		marker = VMapper.createMarker(point, html, {});
		this.map.addOverlay(marker);
	}
}

VMapper.prototype.setUpMarkers = setUpMarkers;

function showCentre(){
	var geocoder = new GClientGeocoder();
	var myVMapper = this;
	
	var blueIcon = new GIcon(G_DEFAULT_ICON);
	blueIcon.image = "/images/blue-dot.png";
	var markerOptions = { icon:blueIcon };

	geocoder.getLocations(this.mapCentreAddress, function(response){
		if (!response || response.Status.code != 200) {
			myVMapper.map.setCenter(myVMapper.mapCentre, 2);		
			console.log("\"Map centre: " + this.mapCentreAddress + "\" not found");
			alert("The centre point location could not be found.");
		} else {
			place = response.Placemark[0];
			point = new GLatLng(place.Point.coordinates[1],
								place.Point.coordinates[0]);
			html = '<h2>Centre</h2>' + place.address + '<br>' + '<b>Country code:</b> ' + place.AddressDetails.Country.CountryNameCode
			marker = VMapper.createMarker(point, html, markerOptions);
			myVMapper.map.mapCentre = point;
			myVMapper.map.setCenter(point, 13);
			myVMapper.map.addOverlay(marker);
		}
	});
}

VMapper.prototype.showCentre = showCentre;

/*
A function to create the marker and set up the event window
Dont try to unroll this function. It has to be here for the function closure
Each instance of the function preserves the contents of a different instance
of the "marker" and "html" variables which will be needed later when the event triggers.  

The createMarker function is independent of any VMapper instance but it is kept 
within the VMapper namespace by making it a class method 
*/
function createMarker(point, html, markerOptions) {
	var marker = new GMarker(point, markerOptions);
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(html);
	});
	return marker;
}

VMapper.createMarker = createMarker;